package com.forest.util;


import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;

import java.security.SecureRandom;

/**
 * 应用加密密匙生成工具.
 *
 * @author Administrator
 */
public class EncryptionKeyUtil {

    private static String SECRET_KEY_SM4 = "emy9oS/otR/Nk9XM9Kv9Hg==";

    private static String SECRET_KEY_AES = "YPEZL1X4am/8cliw4m65vDopy6qAhErIJb36faAcUME=";


    /**
     * 根据加密类型获取密钥
     * @param type          1、SM4  2、AES
     * @return
     */
    public static String getSecretKey(int type) {
        SecureRandom random = new SecureRandom();
        int keyLen = type == 1 ? 16 : 32;
        byte[] key = new byte[keyLen];
        random.nextBytes(key);
        System.out.println("密匙:" + Base64.encode(key));
        byte[] encrypted = type == 1 ? AesUtil.encrypt(Sm4Util.encrypt(key, SECRET_KEY_SM4, null, true), SECRET_KEY_AES, null, true) : Sm4Util.encrypt(AesUtil.encrypt(key, SECRET_KEY_AES, null, true), SECRET_KEY_SM4, null, true);
        return Base64.encode(encrypted);
    }

    /**
     * 获取应用密钥
     * @param type              1、SM4  2、AES
     * @param secretKey         密匙
     * @return
     */
    public static String getAppSecretKey(int type, String secretKey) {
        switch (type) {
            case 1:
                return Base64.encode(Sm4Util.decrypt(AesUtil.decrypt(SecureUtil.decode(secretKey), SECRET_KEY_AES,  null, true), SECRET_KEY_SM4, null, true));
            case 2:
                return Base64.encode(AesUtil.decrypt(Sm4Util.decrypt(SecureUtil.decode(secretKey), SECRET_KEY_SM4, null, true), SECRET_KEY_AES, null, true));
            default:
                return secretKey;
        }
    }

    public static void main(String[] args) {
        String secretKey = getSecretKey(1);
        System.out.println("密匙-SM4:" + secretKey);
        byte[] decrypt = Sm4Util.decrypt(AesUtil.decrypt(SecureUtil.decode(secretKey), SECRET_KEY_AES, null, true), SECRET_KEY_SM4, null, true);
        System.out.println("密匙-解密-SM4:" + Base64.encode(decrypt));
        String secretKey2 = getSecretKey(2);
        System.out.println("密匙-AES:" + secretKey2);
        byte[] decrypt2 = AesUtil.decrypt(Sm4Util.decrypt(SecureUtil.decode(secretKey2), SECRET_KEY_SM4, null, true), SECRET_KEY_AES, null, true);
        System.out.println("密匙-解密-AES:" + Base64.encode(decrypt2));
    }
}
